package com.example.service;

import com.example.domain.College;
import com.example.domain.Major;
import com.example.domain.Student;
import com.example.mapper.CollegeMapper;
import com.example.mapper.MajorMapper;
import com.example.mapper.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 学生服务层
 */
@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private MajorMapper majorMapper;
    @Autowired
    private CollegeMapper collegeMapper;

    public void saveStudent(Student student) {
        Long majorId = student.getMajorId();
        if (majorId != null) {
            Major major = majorMapper.selectByPrimaryKey(majorId);
            student.setMajorName(major.getMajorName());
        }
        Long collegeId = student.getCollegeId();
        if (collegeId != null) {
            College college = collegeMapper.selectByPrimaryKey(collegeId);
            student.setCollegeName(college.getCollegeName());
        }
        if (student.getStudentId() == null) {
            student.setPassword("123456");
            studentMapper.insert(student);
        } else {
            studentMapper.updateByPrimaryKeySelective(student);
        }
    }


    public Student selectStudentByUsernameAndPassword(String username, String password) {
        return this.studentMapper.selectStudentByUsernameAndPassword(username, password);
    }

    public Student selectById(Long id) {
        return this.studentMapper.selectByPrimaryKey(id);
    }

    public void deleteById(Long id) {
        this.studentMapper.deleteByPrimaryKey(id);
    }


    /**
     * 分页
     * @param student
     * @return
     */
    public PageInfo<Student> selectStudentList(Student student) {
        Integer pageNum = student.getPageNum();
        PageHelper.startPage(pageNum, 10, true);
        List<Student> list = studentMapper.selectList(student.getParams());
        return new PageInfo<>(list);
    }
}
